package com.achievo.know.web.news;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.achievo.know.application.AreaApplication;
import com.achievo.know.application.CategoryApplication;
import com.achievo.know.application.FileApplication;
import com.achievo.know.application.NewsApplication;
import com.achievo.know.component.impl.FileManagerConfig;
import com.achievo.know.domain.Area;
import com.achievo.know.domain.AttachmentType;
import com.achievo.know.domain.Category;
import com.achievo.know.domain.FileAttachment;
import com.achievo.know.domain.News;
import com.achievo.know.domain.NewsContent;
import com.achievo.know.domain.TempAttachment;
import com.achievo.know.domain.UserFavorite;
import com.achievo.know.pojo.FileHandle;
import com.achievo.know.pojo.JsonCategory;
import com.achievo.know.pojo.SearchParam;
import com.achievo.know.web.util.PageActionSupport;
import com.dayatang.querychannel.support.Page;
import com.redhat.redwork.coc.RedworkAction;

public class NewsAction extends PageActionSupport implements RedworkAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3766122790859570994L;
	
	private static final Logger	logger  = LoggerFactory.getLogger(NewsAction.class);
	
	@Autowired
	private NewsApplication newsApplication;
	@Autowired
	public FileApplication fileApplication;
	
	private Page<News> newsList;
	
	private String ids;//选择删除的IDS
	
	private String jsonResult;//JSON操作结果
	
	private String jsonCode;
	
	private News n;
	
	private String content;
	
	private String tempFileId;//临时文件ID
	
	private String tempImageId;
	
	private String newsId;
	
	private List<TempAttachment>  tempAttachs;
	
	private List<Area> areas;
	
	private SearchParam params=new SearchParam();
	
	@Autowired
	private AreaApplication areaApplication;
	
	@Autowired
    private FileManagerConfig config;
	
	private int page=1;
	private int attaPage=1;
	
	private String lastRefer;
	
	private Page<FileAttachment> attsPage;	
	
	
	
	public Page<FileAttachment> getAttsPage() {
		return attsPage;
	}
	public void setAttsPage(Page<FileAttachment> attsPage) {
		this.attsPage = attsPage;
	}
	public int getAttaPage(){
		return this.attaPage;
	}
	public void setAttaPage(int page){
		this.attaPage=page;
	}
	public String getLastRefer() {
		return lastRefer;
	}

	public void setLastRefer(String lastRefer) {
		this.lastRefer = lastRefer;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setConfig(FileManagerConfig config) {
		this.config = config;
	}

	public void setAreaApplication(AreaApplication areaApplication) {
		this.areaApplication = areaApplication;
	}

	public List<Area> getAreas() {
		return areas;
	}

	public void setAreas(List<Area> areas) {
		this.areas = areas;
	}

	public List<TempAttachment> getTempAttachs() {
		return tempAttachs;
	}
	
	

	public String getTempImageId() {
		return tempImageId;
	}

	public void setTempImageId(String tempImageId) {
		this.tempImageId = tempImageId;
	}

	public void setTempAttachs(List<TempAttachment> tempAttachs) {
		this.tempAttachs = tempAttachs;
	}

	private String data;
	private String cateText;
	private Category category;
	
	
	public String getCateText() {
		return cateText;
	}

	public void setCateText(String cateText) {
		this.cateText = cateText;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String home(){
		if(StringUtils.isNotEmpty(params.getCategory()) && !"999".equals(params.getCategory())){
			List<Long> cateIds=categoryApplication.listAllIds(Long.parseLong(params.getCategory()));
			newsList=newsApplication.queryPage(cateIds,currentPage, pageSize,params,false);
			Category c=categoryApplication.get(Long.parseLong(params.getCategory()));
			cateText=c.getName();
		}else{
			if(isSuperAdmin())
				newsList=newsApplication.queryPage(null,currentPage, pageSize,params,true);
			else
				newsList=newsApplication.queryPage(getAdminCateIds(),currentPage, pageSize,params,false);
		}
		areas=areaApplication.findAll();
		if(isSuperAdmin())
			data=categoryApplication.getJsonWithRoot(null);
		else
			data=categoryApplication.getJsonWithRoot(getAdminCateIds());
		return "home";
	}

	/**
	 * 删除
	 * @return
	 */
	public String delBatch(){
		try{
			if(StringUtils.isNotEmpty(ids)){
				String[] idArr=ids.split(",");
				newsApplication.batchDelete(idArr);
				jsonResult="删除成功!";
				jsonCode="1";
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			jsonResult="出错："+e.getMessage();
			jsonCode="0";
		}
		return JSON;
	}
	
	public String goPublish(){
		tempFileId=UUID.randomUUID().toString().replaceAll("-", "");//生成临时文件ID
		tempImageId=UUID.randomUUID().toString().replaceAll("-", "");
		areas=areaApplication.findAll();
		lastRefer=getReferrer();
		return "news-publish";
	}
	
	public String save(){
		if("on".equals(n.getCanFaqStr())){
			n.setCanFaq(true);
		}else{
			n.setCanFaq(false);
		}
		if("on".equals(n.getCanDownStr())){
			n.setCanDown(true);
		}else{
			n.setCanDown(false);
		}
		n.setPublishTime(new Date());
		n.setSugestTime(new Date());
		n.setPublishUser(getUserId());
		//n.setPublishUserName(getUserRealName());
		n.setBrowserNum(0);
		n.setFaqSum(0);
		NewsContent cont=new NewsContent();
		cont.setContent(content);
		cont.setNews(n);
		Set<NewsContent> conts=new HashSet<NewsContent>();
		conts.add(cont);
		n.setContent(conts);
		List<TempAttachment>  tempAttachs=fileApplication.loadTempAttach(tempFileId);
		List<FileAttachment> atts=new ArrayList<FileAttachment>();
		for(TempAttachment temp:tempAttachs){
			FileAttachment a=new FileAttachment();
			a.setAttachName(temp.getAttachName());
			a.setAttachPath(temp.getAttachPath());
			a.setAttachSize(temp.getAttachSize());
			AttachmentType type=new AttachmentType();
			type.setName(temp.getAttachType());
			type.setIcon("");
			a.setAttachType(type);
			a.setGuid(temp.getGuid());
			//set image
			final List<TempAttachment>  tempImages=fileApplication.loadTempAttach(temp.getGuid());
			if(tempImages.size()>0){
				a.setPhotoName(tempImages.get(0).getGuid()+"."+tempImages.get(0).getAttachType());
				FileHandle.move(config.getUploadFileStoreDirectory(), config.getImageStoreDirectory(), tempImages.get(0));
			}
			atts.add(a);
		}
		n.setAttachments(atts);
		List<TempAttachment>  tempImages=fileApplication.loadTempAttach(tempImageId);
		if(tempImages.size()>0){
			TempAttachment temp=tempImages.get(0);
			final FileAttachment a=new FileAttachment();
			a.setAttachName(temp.getAttachName());
			a.setAttachPath(temp.getAttachPath());
			a.setAttachSize(temp.getAttachSize());
			AttachmentType type=new AttachmentType();
			type.setName(temp.getAttachType());
			type.setIcon("");
			a.setAttachType(type);
			a.setGuid(temp.getGuid());
			atts.add(a);
			n.setNewsImage(a);
			FileHandle.move(config.getUploadFileStoreDirectory(), config.getImageStoreDirectory(), a);
		}
		if(areas!=null && areas.size()>0){
			Set<Area> setArea=new HashSet<Area>();
			for(Area a:areas){
				if(a==null)
					continue;
				Area t=areaApplication.get(a.getId());
				setArea.add(t);
			}
			n.setAreas(setArea);
		}
		newsApplication.add(n);
		return "save-success";
	}
	
	public String edit(){
		if("on".equals(n.getCanFaqStr())){
			n.setCanFaq(true);
		}else{
			n.setCanFaq(false);
		}
		if("on".equals(n.getCanDownStr())){
			n.setCanDown(true);
		}else{
			n.setCanDown(false);
		}
		n.setEditTime(new Date());
		n.setEditUser(getUserId());
		NewsContent cont=new NewsContent();
		cont.setContent(content);
		cont.setNews(n);
		Set<NewsContent> conts=new HashSet<NewsContent>();
		conts.add(cont);
		n.setContent(conts);
		List<TempAttachment>  tempAttachs=fileApplication.loadTempAttach(tempFileId);
		List<FileAttachment> atts=new ArrayList<FileAttachment>();
		for(TempAttachment temp:tempAttachs){
			FileAttachment a=new FileAttachment();
			a.setAttachName(temp.getAttachName());
			a.setAttachPath(temp.getAttachPath());
			a.setAttachSize(temp.getAttachSize());
			AttachmentType type=new AttachmentType();
			type.setName(temp.getAttachType());
			type.setIcon("");
			a.setAttachType(type);
			a.setGuid(temp.getGuid());
			a.setFkType(temp.getFkType());
			//set image
			final List<TempAttachment>  tempImages=fileApplication.loadTempAttach(temp.getGuid());
			if(tempImages.size()>0){
				a.setPhotoName(tempImages.get(0).getGuid()+"."+tempImages.get(0).getAttachType());
				FileHandle.move(config.getUploadFileStoreDirectory(), config.getImageStoreDirectory(), tempImages.get(0));
			}
			atts.add(a);
		}
		List<TempAttachment>  tempImages=fileApplication.loadTempAttach(tempImageId);
		if(tempImages.size()>0){
			TempAttachment temp=tempImages.get(0);
			final FileAttachment a=new FileAttachment();
			a.setAttachName(temp.getAttachName());
			a.setAttachPath(temp.getAttachPath());
			a.setAttachSize(temp.getAttachSize());
			AttachmentType type=new AttachmentType();
			type.setName(temp.getAttachType());
			type.setIcon("");
			a.setAttachType(type);
			a.setGuid(temp.getGuid());
			a.setFkType(temp.getFkType());
			//atts.add(a);
			n.setNewsImage(a);
		}
		n.setAttachments(atts);
		if(areas!=null && areas.size()>0){
			Set<Area> setArea=new HashSet<Area>();
			for(Area a:areas){
				if(a==null)
					continue;
				Area t=areaApplication.get(a.getId());
				setArea.add(t);
			}
			n.setAreas(setArea);
		}
		newsApplication.edit(n);
		return "edit-success";
	}
	/**
	 * 显示资讯
	 * @return
	 */
	public String showNews(){
		if(StringUtils.isNotEmpty(newsId)){
			cates=categoryApplication.getRoots();
			n=newsApplication.showNews(Long.parseLong(newsId),page==1&&attaPage==1?true:false);
			List<FileAttachment> temp=new ArrayList<FileAttachment>();
			List<FileAttachment> atts=n.getAttachments();
			int size=atts.size();
			int pageSize=Integer.parseInt(config.getConfigHolder().getConfig("attaSize"));
			int index=(attaPage-1)*pageSize;
			for(int i=0;i<size;i++){
				if(i>=index && i<index+pageSize){
					temp.add(atts.get(i));
				}
			}
			attsPage=new Page<FileAttachment>(0,size,pageSize,temp);
			if(n.getCategoryId()!=null){
			category=categoryApplication.get(n.getCategoryId());
			navCates=new ArrayList<Category>();
			navCates.add(category);
			Category p=category.getParent();
			while(p!=null){
				navCates.add(p);
				p=p.getParent();
			}
			}
		}
		List<Long> cs=null;
		if(!isSuperAdmin()){
			cs=getUserCateIds();
		}
		cates1=categoryApplication.getCates(cs);
		return "news_show";
	}
	
	/**
	 * 显示编辑页面
	 * @return
	 */
	public String gotoEdit(){
		if(StringUtils.isNotEmpty(newsId)){
			tempFileId=UUID.randomUUID().toString().replaceAll("-", "");//生成临时文件ID
			tempImageId=UUID.randomUUID().toString().replaceAll("-", "");
			n=newsApplication.showEditNews(Long.parseLong(newsId),tempFileId,tempImageId);
			tempAttachs=fileApplication.loadTempAttach(tempFileId);
			areas=areaApplication.findAll();
		}
		lastRefer=getReferrer();
		return "edit-news";
	}

	private List<Category> cates;
	
	private List<Category> navCates;
	
	@Autowired
	private CategoryApplication categoryApplication;
	
	
	private List<JsonCategory> cates1;
	
	
	
	public List<JsonCategory> getCates1() {
		return cates1;
	}
	public void setCates1(List<JsonCategory> cates1) {
		this.cates1 = cates1;
	}
	public List<Category> getCates() {
		return cates;
	}

	public void setCates(List<Category> cates) {
		this.cates = cates;
	}

	public void setCategoryApplication(CategoryApplication categoryApplication) {
		this.categoryApplication = categoryApplication;
	}

	public void setNewsApplication(NewsApplication newsApplication) {
		this.newsApplication = newsApplication;
	}


	public Page<News> getNewsList() {
		return newsList;
	}


	public void setNewsList(Page<News> newsList) {
		this.newsList = newsList;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {
		this.jsonResult = jsonResult;
	}

	public String getJsonCode() {
		return jsonCode;
	}

	public void setJsonCode(String jsonCode) {
		this.jsonCode = jsonCode;
	}

	public News getN() {
		return n;
	}

	public void setN(News n) {
		this.n = n;
	}

	public String getTempFileId() {
		return tempFileId;
	}

	public void setTempFileId(String tempFileId) {
		this.tempFileId = tempFileId;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setFileApplication(FileApplication fileApplication) {
		this.fileApplication = fileApplication;
	}

	public String getNewsId() {
		return newsId;
	}

	public void setNewsId(String newsId) {
		this.newsId = newsId;
	}
	
	public Long lid(Long id){
		return newsApplication.getLid(id);
	}
	
	public Long rid(Long id){
		return newsApplication.getRid(id);
	}
	
	public Long top(){
		return newsApplication.getTop();
	}
	public String changePosition(){
		try{
			News onew=newsApplication.get(Long.parseLong(newsId));
			if(onew==null){
				throw new RuntimeException("找不到该资讯");
			}
			newsApplication.beforePosition(onew,ids);
			jsonCode="1";
			jsonResult="保存成功";
		}catch (Exception e) {
			jsonCode="0";
			jsonResult="保存出错："+e.getMessage();
		}
		return JSON;
	}
	
	/**
	 * 添加收藏
	 * @return
	 */
	public String addFavorite(){
		try{
			UserFavorite uf=new UserFavorite();
			uf.setFileId(Long.parseLong(newsId));
			newsApplication.addFavorite(uf,getUserId());
			jsonResult="保存成功!";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			jsonResult="出错："+e.getMessage();
		}
		return JSON;
	}

	public SearchParam getParams() {
		return params;
	}

	public void setParams(SearchParam params) {
		this.params = params;
	}
	
	@Override
	public String getParam() {
		StringBuilder b=new StringBuilder();
		b.append("search=true");
		if(StringUtils.isNotEmpty(params.getAreaName())){
			b.append("&params.areaName="+params.getAreaName());
		}
		if(StringUtils.isNotEmpty(params.getTitle())){
			b.append("&params.title="+params.getTitle());
		}
		if(StringUtils.isNotEmpty(params.getCategory())){
			b.append("&params.category="+params.getCategory());
		}
		return b.toString();
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public List<Category> getNavCates() {
		return navCates;
	}

	public void setNavCates(List<Category> navCates) {
		this.navCates = navCates;
	}
	
}
